package example.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class UploadImage extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
		try {
            req.getRequestDispatcher("/pages/upload_image.jsp").forward(req, resp);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		// Get the image representations
		try {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setSizeMax(500000);

			try {
				FileItemIterator iterator = upload.getItemIterator(req);
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream in = item.openStream();
					
					if (item.isFormField()) {
						//out.println("Got a form field: " + item.getFieldName());
						System.out.println("Got a form field: " + item.getFieldName());
					} else {
						String fieldName = item.getFieldName();
						String fileName = item.getName();
						String contentType = item.getContentType();
						
						System.out.println("--------------");
						System.out.println("fileName = " + fileName);
						System.out.println("field name = " + fieldName);
						System.out.println("contentType = " + contentType);
						
						String fileContents = null;
						try {
							resp.setContentType(contentType);
							byte barr[]  = IOUtils.toByteArray(in);
							resp.setContentLength(barr.length);
							resp.getOutputStream().write(barr);
						} finally {
							IOUtils.closeQuietly(in);
						}

					}
				}
			} catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) {
				System.out.println("You exceeded the maximu size ("
						+ e.getPermittedSize() + ") of the file ("
						+ e.getActualSize() + ")");
			}
		} catch (Exception ex) {
			//throw new ServletException(ex);
			ex.printStackTrace();
		}
	}
}
